﻿//
// (C) Copyright 2009 Irantha Suwandarathna (iranthas@hotmail.com)
// All rights reserved.
//

/* Copyright (c) 2001-2008, The HSQL Development Group
 * All rights reserved.
 *
 * Redistribution and use _in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 *
 * Redistributions _in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer _in the documentation
 * and/or other materials provided with the distribution.
 *
 * Neither the name of the HSQL Development Group nor the names of its
 * contributors may be used to endorse or promote products derived from this
 * software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL HSQL DEVELOPMENT GROUP, HSQLDB.ORG,
 * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using EffiProz.Core.Lib;
using EffiProz.Core.RowIO;
using EffiProz.Core.Errors;
using EffiProz.Core.Indexes;
using EffiProz.Core.Navigators;


namespace EffiProz.Core.Persist
{
    public class RowStoreAVLMemory : RowStoreAVL
    {
        Table table;
        private IntKeyHashMapConcurrent rowIdMap;
        int rowIdSequence = 0;

        public RowStoreAVLMemory(PersistentStoreCollection manager, Table table)
        {

            this.manager = manager;
            this.table = table;
            this.indexList = table.getIndexList();
            this.accessorList = new CachedObject[indexList.Length];
            rowIdMap = new IntKeyHashMapConcurrent();

            manager.setStore(table, this);
        }

        public override bool isMemory()
        {
            return true;
        }

        public override int getAccessCount()
        {
            return 0;
        }

        public override void set(CachedObject obj) { }

        public override CachedObject get(int i)
        {
            return (CachedObject)rowIdMap.get(i);
        }

        public CachedObject getKeep(int i)
        {
            return (CachedObject)rowIdMap.get(i);
        }

        public override CachedObject get(int i, bool keep)
        {
            return (CachedObject)rowIdMap.get(i);
        }

        public override CachedObject get(CachedObject obj, bool keep)
        {
            return (CachedObject)rowIdMap.get(obj.getPos());
        }

        public override int getStorageSize(int i)
        {
            return 0;
        }

        public override void add(CachedObject obj) { }

        public override CachedObject get(RowInputInterface _in)
        {
            return null;
        }

        public override CachedObject getNewCachedObject(Session session, Object obj)
        {

            Row row = new RowAVL(table, (Object[])obj);

            if (session != null)
            {
                RowAction.addAction(session, RowAction.ACTION_INSERT, table, row);
            }

            lock (this)
            {
                int id = rowIdSequence++;

                row.setPos(id);
                rowIdMap.put(id, row);
            }

            return row;
        }

        public override void removeAll()
        {
            rowIdMap.clear();
            ArrayUtil.fillArray(accessorList, null);
        }

        public override void remove(int i)
        {
            rowIdMap.remove(i);
        }

        public override void removePersistence(int i) { }

        public override void release(int i) { }

        public override void commitPersistence(CachedObject row) { }

        public override DataFileCache getCache()
        {
            return null;
        }

        public override void setCache(DataFileCache cache) { }

        public override void release()
        {
            ArrayUtil.fillArray(accessorList, null);
            rowIdMap.clear();
        }

        public override void setAccessor(Index key, CachedObject accessor)
        {

            Index index = (Index)key;

            accessorList[index.getPosition()] = accessor;
        }

        public override void setAccessor(Index key, int accessor) { }

        public override void resetAccessorKeys(Index[] keys)
        {

            if (indexList.Length == 0 || indexList[0] == null
                    || accessorList[0] == null)
            {
                indexList = keys;
                accessorList = new CachedObject[indexList.Length];

                return;
            }

            CachedObject[] oldAccessors = accessorList;
            Index[] oldIndexList = indexList;
            int limit = indexList.Length;
            int diff = 1;
            int position = 0;

            if (keys.Length < indexList.Length)
            {
                diff = -1;
                limit = keys.Length;
            }

            for (; position < limit; position++)
            {
                if (indexList[position] != keys[position])
                {
                    break;
                }
            }

            accessorList = (CachedObject[])ArrayUtil.toAdjustedArray(accessorList,
                    null, position, diff);
            indexList = keys;

            try
            {
                if (diff > 0)
                {
                    insertIndexNodes(indexList[0], indexList[position]);
                }
                else
                {
                    dropIndexFromRows(indexList[0], oldIndexList[position]);
                }
            }
            catch (CoreException e)
            {
                accessorList = oldAccessors;
                indexList = oldIndexList;

                throw e;
            }
        }

        public override CachedObject getNewInstance(int size)
        {
            return null;
        }

        void dropIndexFromRows(Index primaryIndex, Index oldIndex)
        {

            RowIterator it = primaryIndex.firstRow(this);
            int position = oldIndex.getPosition() - 1;

            while (it.hasNext())
            {
                Row row = it.getNextRow();
                int i = position - 1;
                NodeAVL backnode = ((RowAVL)row).getNode(0);

                while (i-- > 0)
                {
                    backnode = backnode.nNext;
                }

                backnode.nNext = backnode.nNext.nNext;
            }
        }

        bool insertIndexNodes(Index primaryIndex, Index newIndex)
        {

            int position = newIndex.getPosition();
            RowIterator it = primaryIndex.firstRow(this);
            int rowCount = 0;
            CoreException error = null;

            try
            {
                while (it.hasNext())
                {
                    Row row = it.getNextRow();

                    ((RowAVL)row).insertNode(position);

                    // count before inserting
                    rowCount++;

                    newIndex.insert(null, this, row);
                }

                return true;
            }
            catch (OutOfMemoryException )
            {
                error = Error.error(ErrorCode.OUT_OF_MEMORY);
            }
            catch (CoreException e)
            {
                error = e;
            }

            // backtrack on error
            // rowCount rows have been modified
            it = primaryIndex.firstRow(this);

            for (int i = 0; i < rowCount; i++)
            {
                Row row = it.getNextRow();
                NodeAVL backnode = ((RowAVL)row).getNode(0);
                int j = position;

                while (--j > 0)
                {
                    backnode = backnode.nNext;
                }

                backnode.nNext = backnode.nNext.nNext;
            }

            throw error;
        }

        /**
         * for result tables
         */
        void reindex(Session session, Index index)
        {

            setAccessor(index, null);

            RowIterator it = table.rowIterator(session);

            while (it.hasNext())
            {
                Row row = it.getNextRow();

                // may need to clear the node before insert
                index.insert(session, this, row);
            }
        }
    }
}
